package com.example.jwtauthdemo.service.impl;

import com.example.jwtauthdemo.mapper.UserMapper;
import com.example.jwtauthdemo.model.User;
import com.example.jwtauthdemo.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    
    @Autowired
    public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getRealNameAuthStatus(Long userId) {
        logger.info("查询用户ID: {} 的实名认证状态", userId);
        Map<String, Object> statusMap = userMapper.getRealNameAuthStatus(userId);
        
        // 如果查询结果为空，返回未认证状态
        if (statusMap == null) {
            logger.warn("未找到用户ID: {} 的信息", userId);
            statusMap = Map.of("isVerified", false, "message", "用户信息不存在");
        }
        
        return statusMap;
    }
    
    @Override
    public Optional<User> findById(Long id) {
        return userMapper.findById(id);
    }
    
    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        logger.info("用户ID: {} 请求更改密码", userId);
        
        // 打印未加密的原密码和新密码到控制台
        System.out.println("用户ID: " + userId + " 请求更改密码");
        System.out.println("未加密的原密码: " + oldPassword);
        System.out.println("未加密的新密码: " + newPassword);
        
        try {
            // 查询用户信息
            User user = userMapper.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 验证原密码是否正确
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                logger.warn("用户ID: {} 原密码验证失败", userId);
                return false;
            }
            
            // 检查新密码是否与原密码相同
            if (passwordEncoder.matches(newPassword, user.getPassword())) {
                logger.warn("用户ID: {} 新密码与原密码相同", userId);
                return false;
            }
            
            // 加密新密码并更新
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdateTime(LocalDateTime.now());
            int rowsAffected = userMapper.update(user);
            
            if (rowsAffected > 0) {
                logger.info("用户ID: {} 密码更改成功", userId);
                return true;
            } else {
                logger.warn("用户ID: {} 密码更改失败，数据库更新无影响行", userId);
                return false;
            }
        } catch (Exception e) {
            logger.error("用户ID: {} 密码更改异常: {}", userId, e.getMessage(), e);
            throw new RuntimeException("密码更改失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public String getRealNameById(Long userId) {
        logger.info("查询用户ID: {} 的真实姓名", userId);
        
        try {
            // 查询用户信息
            User user = userMapper.findById(userId)
                    .orElse(null);
            
            if (user == null) {
                logger.warn("未找到用户ID: {} 的信息", userId);
                return null;
            }
            
            logger.info("用户ID: {} 的真实姓名查询成功", userId);
            return user.getRealName();
        } catch (Exception e) {
            logger.error("查询用户ID: {} 的真实姓名异常: {}", userId, e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    @Transactional
    public boolean updateUser(User user) {
        logger.info("更新用户ID: {} 的信息", user.getId());
        
        try {
            // 验证用户是否存在
            User existingUser = userMapper.findById(user.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 设置更新时间
            user.setUpdateTime(LocalDateTime.now());
            
            // 调用mapper更新用户信息
            int rowsAffected = userMapper.update(user);
            
            if (rowsAffected > 0) {
                logger.info("用户ID: {} 信息更新成功", user.getId());
                return true;
            } else {
                logger.warn("用户ID: {} 信息更新失败，数据库更新无影响行", user.getId());
                return false;
            }
        } catch (Exception e) {
            logger.error("用户ID: {} 信息更新异常: {}", user.getId(), e.getMessage(), e);
            throw new RuntimeException("用户信息更新失败: " + e.getMessage(), e);
        }
    }
}